package org.streets.eis.component.tree;

import java.io.Serializable;

import javax.swing.tree.DefaultMutableTreeNode;

/**
 * 若自己造完整的树(不需要分级读取的)，需要手功将已加载的node的loaded设为true
 *  
 */
public class Node<T extends Serializable> extends DefaultMutableTreeNode {
	
	private static final long serialVersionUID = 1L;
	
	private boolean loading = false;
	private boolean loaded = false;

	public Node(T object) {
		this(object, true);
	}
	
	public Node(T object, boolean allowsChildren) {
		super(object,allowsChildren);
	}
	
	public boolean isLoaded() {
		return loaded;
	}
	
	public Node<T> setLoaded(boolean loaded) {
		this.loaded = loaded;
		return this;
	}
	
	@SuppressWarnings("unchecked")
	public T getObject() {		
		return (T) getUserObject();
	}	

	@Override
	public boolean isLeaf() {
		loadChildren();
		return super.isLeaf();
	}

	@SuppressWarnings("unchecked")
	public void loadChildren() {
		if (getAllowsChildren() && !loaded && !loading) {
			loading = true;
			try {
				removeAllChildren();
				Node<T> parent = this;
				while(parent.getParent()!=null){
					parent = (Node<T>) parent.getParent();
				}
				parent.load(this);
			} finally {
				loading = false;
				loaded = true;
			}
		}
	}
	
	protected void load(Node<T> node){		
	}
}	